package com.dongrj.framework.web.utils;

import com.dongrj.framework.core.constant.Constant;
import org.springframework.context.ApplicationContext;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author dongrongjun
 * @date 2020/4/2
 */
public class SpringUtils {

    private static ApplicationContext applicationContext;

    public static String getConfigValue(String paramKey) {
        return getConfigValue(paramKey, null);
    }

    public static String getConfigValue(String paramKey, String defaultValue) {
        return applicationContext.getEnvironment().getProperty(paramKey, defaultValue);
    }

    public static String getActiveEnv() {
        return getConfigValue(Constant.App.SPRING_ACTIVE);
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }


    public static <T> List<T> getBeanList(Class<T> interfaceClass) {
        Map<String, T> beansOfType = applicationContext.getBeansOfType(interfaceClass);
        Collection<T> values = beansOfType.values();
        return new ArrayList<>(values);
    }

    public static <T extends Annotation> Map<String, Object> getBeansWithAnnotation(Class<T> cls) {
        return applicationContext.getBeansWithAnnotation(cls);
    }


    public static <T extends Annotation> String[] getBeanNamesForAnnotation(Class<T> cls) {
        return applicationContext.getBeanNamesForAnnotation(cls);
    }

    public static String[] getBeanDefinitionNames() {
        return applicationContext.getBeanDefinitionNames();
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        if (SpringUtils.applicationContext == null) {
            SpringUtils.applicationContext = applicationContext;
        }
    }

    public static void configApplicationContext(ApplicationContext applicationContext) {
        if (SpringUtils.applicationContext == null) {
            SpringUtils.applicationContext = applicationContext;
        }
    }

}
